#include "stdafx.h"
#include "McuHandler.h"
#include "McuManager.h"
#include "VanException.h"
#include "CmdServer.h"
#include "McuCmd.h"
#include "Utils.h"
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "common.h"

McuHandler* McuHandler::m_pInstance = NULL;

McuHandler::McuHandler()
{
}

McuHandler::~McuHandler()
{
}

McuHandler* McuHandler::Instance()
{
	if (NULL == m_pInstance) {
		m_pInstance = new McuHandler();
	}

	return m_pInstance;
}

void McuHandler::SpecialResp(byte nCmd, byte* pData, int length)
{
	Packet packet(nCmd + 0x80);

	if (NULL!=pData && length>0) {
		packet.SetBody(pData, length);
	}
	
	Packet* pResp = NULL;

	try {
		pResp = McuManager::Instance()->Request(&packet, false);
	} catch (VanException* e) {
	}
}

void McuHandler::GeneralResp(byte nCmd, byte result)
{
	byte buf[2];
	buf[0] = nCmd;
	buf[1] = result;

	Packet packet(0x80);
	packet.SetBody(buf, 2);
	
	Packet* pResp = NULL;

	try {
		pResp = McuManager::Instance()->Request(&packet, false);
	} catch (VanException* e) {
	}
}

void McuHandler::Handle(Packet* pPacket)
{
	int nCmd = pPacket->GetCMD();

	switch (nCmd)
	{
	case PCID_ACC_PUSH:
		OnAccState(pPacket);
		break;
	case PCID_INPUT_PUSH:
		OnInput(pPacket);
		break;
	case PCID_CAN_READ:
		CanRead(pPacket);
		break;
	}

	delete pPacket;
}

void McuHandler::OnAccState(Packet* pPacket)
{
	const byte* pBody = pPacket->GetBody();

	pPacket->Build();
	CmdServer::Instance()->CallbackSend(ACC, 
		pPacket->GetBuffer(), pPacket->GetLength());
}

void McuHandler::OnInput(Packet* pPacket)
{
	const byte* pBody = pPacket->GetBody();

	pPacket->Build();
	CmdServer::Instance()->CallbackSend(INPUT, 
		pPacket->GetBuffer(), pPacket->GetLength());
}

void McuHandler::CanRead(Packet* pPacket)
{
	pPacket->Build();
	CmdServer::Instance()->CallbackSend(CAN, 
		pPacket->GetBuffer(), pPacket->GetLength());
}
